import fly from 'flyio';
import store from '../store'

fly.config.baseURL = '/api';
//添加请求拦截器
fly.interceptors.request.use((request) => {
    //给所有请求添加自定义header
    request.headers["X-Tag"] = "flyio";
    let userInfo = store.state.userInfo;
    if (userInfo && userInfo.token){
        request.headers.token = userInfo.token;

        if (request.method == 'POST'){
            if (request.body){
                request.body = request.body + `&token=${userInfo.token}&uid=${userInfo.passenger.passengerid}`
            } else {
                request.body = `token=${userInfo.token}&uid=${userInfo.passenger.passengerid}`

            }
        }else if (request.method == 'GET') {

        }
    }

    //打印出请求体

    //终止请求
    //var err=new Error("xxx")
    //err.request=request
    //return Promise.reject(new Error(""))

    //可以显式返回request, 也可以不返回，没有返回值时拦截器中默认返回request
    return request;
})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
    (response) => {
        //只将请求结果的data字段返回
        if (response.data) {
            let data = response.data;
            data = JSON.parse(data)
            let code = data.code;
            if (code == 200) {
                return data;
            } else {
                return Promise.reject(data.msg)
            }
        }
    },
    (err) => {
        //发生网络错误后会走到这里
        return Promise.reject(err.message)
    }
)
export default fly;